package com.qust.EnDecryption.handle;

import io.netty.channel.*;
import lombok.extern.log4j.Log4j2;

import java.net.SocketAddress;

/**
 * netty全局异常捕获
 */
@Log4j2
public class ExceptionHandler extends ChannelDuplexHandler {
    /**
     * 用来捕获入站异常
     *
     * @param ctx
     * @param cause
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        // Uncaught exceptions from inbound handlers will propagate up to this handler
        log.error("Uncaught exceptions from inbound handlers,{}", cause.getMessage());
    }

    /**
     * 连接异常
     *
     * @param ctx
     * @param remoteAddress
     * @param localAddress
     * @param promise
     */
    @Override
    public void connect(ChannelHandlerContext ctx, SocketAddress remoteAddress, SocketAddress localAddress, ChannelPromise promise) {
        ctx.connect(remoteAddress, localAddress, promise.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) {
                if (!future.isSuccess()) {
                    // Handle connect exception here...
                    Throwable failureCause = future.cause();
                    log.error(failureCause.getMessage());
                }
            }
        }));
    }

    /**
     * 出站异常
     *
     * @param ctx
     * @param msg
     * @param promise
     */
    @Override
    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) {
        ctx.write(msg, promise.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) {
                if (!future.isSuccess()) {
                    // Handle write exception here...
                    Throwable failureCause = future.cause();
                }
            }
        }));
    }

    // ... override more outbound methods to handle their exceptions as well
}